﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BL.Entity;
using System.Data.SqlClient;
using System.Transactions;
using DL;
namespace BL.Service
{
    public class tbl_FunctionService : ServiceBase
    {
        public List<Function> FindPermission(int UserID)
        {
            List<Function> result = new List<Function>();
            StringBuilder sql = new StringBuilder();
            sql.AppendLine(" SELECT ");
            sql.AppendLine("F.FunctionCode ");
            sql.AppendLine(",F.FunctionName ");
            sql.AppendLine(",CAST(CASE WHEN U.UserID IS NOT NULL THEN 1 ELSE 0 END as bit) HavePermission   ");

            sql.AppendLine("FROM tbl_Function F ");
            sql.AppendLine("LEFT JOIN tbl_Permission P ON F.FunctionCode=P.FunctionCode ");
            sql.AppendLine("LEFT JOIN tbl_User U ON P.UserID=P.UserID  AND U.UserID=@UserID ");


            List<SqlParameter> param = new List<SqlParameter>();
            param.Add(base.CreateParamater("UserID", UserID));

            result = this.Context.ExecuteStoreQuery<Function>(sql.ToString(), param.ToArray()).ToList();
            return result.ToList();
        }
        public void SaveFunctionPermission(int UserID, List<Function> function, string UserNameUpdate)
        {

            DateTime datenow = this.GetDateGobal();
            TransactionOptions tranOpt = new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted };
            using (var trans = new TransactionScope(TransactionScopeOption.Required, tranOpt))
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine(" DELETE FROM tbl_Permission WHERE UserID=@UserID ");

                List<SqlParameter> param = new List<SqlParameter>();
                param.Add(base.CreateParamater("UserID", UserID));

                this.Context.ExecuteStoreCommand(sql.ToString(), param.ToArray());
                foreach (Function functionItem in function.Where(s=>s.HavePermission==true).ToList())
                {
                    tbl_Permission permission = new tbl_Permission()
                    {
                        CreateDate = datenow,
                        CreateBy = UserNameUpdate,
                        FunctionCode = functionItem.FunctionCode,
                        UpdateBy = UserNameUpdate,
                        UpdateDate = datenow,
                        UserID = UserID
                    };
                    this.Context.AddTotbl_Permission(permission);
                }
                this.Context.SaveChanges();
                trans.Complete();

            }
        }
    }
}
